package com.water_work_form.authority;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class Authority {

    /**
     * 鉴权集合名称
     */
    private final String authorizationSetName = "authorizationSetName";

    @Value("${authority.timeout}")
    private Long timeout;

    @Value("${authority.token-secret}")
    private String tokenSecret;

    public String getToken(String account){
        Date expireAt = new Date(System.currentTimeMillis() + timeout);
        return JWT.create()
                .withAudience(account)
                .withExpiresAt(expireAt)
                .sign(Algorithm.HMAC256(tokenSecret));
    }

    public String getAccount(String token){
        return JWT.decode(token).getAudience().get(0);
    }

    public boolean checkToken(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(tokenSecret)).build();
        jwtVerifier.verify(token);
        return true;
    }
}
